<template>
	<!--  编辑弹框-->
	<el-dialog :model-value="dialogVisible" :show-close="false" :before-close="handleClose" width="35%">
		<template #header="{ titleId, titleClass }">
			<div class="my-header">
				<h4 :id="titleId" :class="titleClass">{{ headerTitle }}</h4>
				<el-button type="danger" plain size="small" :icon="CircleCloseFilled" @click="handleClose"> 关闭弹框 </el-button>
			</div>
		</template>
		<el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="ruleForm" :size="formSize" status-icon>
			<el-form-item label="收藏账户" prop="uid">
				<el-select v-model="form.uid">
					<el-option v-for="(item, index) in userList" :key="index.toString()" :label="item.username" :value="item.id"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="所属视频" prop="vid">
				<el-select v-model="form.vid">
					<el-option v-for="(item, index) in videoList" :key="index.toString()" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleResetForm(ruleFormRef)">取消</el-button>
				<el-button type="primary" @click="handleSubmitForm(ruleFormRef)"> 提交 </el-button>
			</span>
		</template>
	</el-dialog>

	<el-row style="width: 80%; margin: 0 auto; position: relative; top: 60px">
		<!--  分页查询表单按钮-->
		<el-col>
			<el-form :inline="true">
				<el-row>
					<el-col>
						<el-form-item label-width="5px">
							<el-select v-model="vid" placeholder="请选择所属视频" style="width: 200px" clearable @change="load" @clear="load">
								<el-option v-for="(item, index) in videoList" :key="index.toString()" :label="item.name" :value="item.id"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label-width="5px">
							<el-button type="primary" :icon="Search" @click="load"> 查询 </el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-col>
		<el-col>
			<el-table
				:data="tableData"
				style="width: 100%"
				:header-cell-style="{ background: '#eef1f6', color: '#606266' }"
				@selection-change="handleSelectionChange"
			>
				<el-table-column prop="vid" label="所属视频" align="center">
					<template #default="scope">
						<span v-if="scope.row.video">{{ scope.row.video.name }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="收藏时间" align="center" />

				<el-table-column label="操作" align="center">
					<template #default="scope">
						<div style="display: flex; justify-content: center; gap: 10px">
							<div>
								<el-button type="primary" :icon="View" size="small" @click="handleUpdate(scope.row.vid)"> 查看 </el-button>
							</div>
							<div>
								<el-popconfirm
									confirm-button-text="确定"
									cancel-button-text="取消"
									:icon="InfoFilled"
									icon-color="#626AEF"
									title="确认要删除吗？"
									@confirm="handleDel(scope.row.id)"
									@cancel="load"
								>
									<template #reference>
										<el-button type="danger" :icon="Delete" size="small"> 取消收藏 </el-button>
									</template>
								</el-popconfirm>
							</div>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<!--      分页按钮-->
			<div class="pagination">
				<el-pagination
					:current-page="pageNum"
					:page-size="pageSize"
					:page-sizes="[10, 20, 30, 50, 100, 500, 1000]"
					size="small"
					layout="total, sizes, prev, pager, next, jumper"
					:total="Number(total)"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</el-col>
	</el-row>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { CircleCloseFilled, Delete, Download, Edit, InfoFilled, Plus, Refresh, Search, Upload, View } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import downloadExcel from '@/utils/downloads'
import 'md-editor-v3/lib/style.css'
import router from '@/router'

const headerTitle = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const disabled = ref(true)
const dialogVisible = ref(false)
const userList = ref([])
const videoList = ref([])
const uid = ref('')
const vid = ref('')
const formSize = ref('default')
const ruleFormRef = ref()

// 表单数据定义
const form = reactive({
	id: undefined,
	uid: undefined,
	vid: undefined,
	createTime: undefined
})

// 表单校验规则
const rules = reactive({
	uid: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	vid: [{ required: true, message: '必选项不能为空', trigger: 'change' }]
})

//新增方法
const handleAdd = async () => {
	headerTitle.value = reactive('新增数据')
	dialogVisible.value = true
}
const $route = router

// 修改方法
const handleUpdate = async id => {
	$route.push(`/front/video/detail?id=${id}`)
}

// 单个删除方法
const handleDel = async id => {
	await request.delete(`/video/collect/${id}`)
	ElMessage({
		showClose: true,
		message: '删除成功',
		type: 'success'
	})
	await load()
}

// 批量删除方法
const handleBatchDel = async () => {
	const ids = []
	multipleSelection.value.forEach(row => {
		ids.push(row.id)
	})
	await request.delete(`/video/collect/batch/${ids}`)
	ElMessage({
		showClose: true,
		message: '批量删除成功',
		type: 'success'
	})
	await load()
}

// 分页查询方法（初始化方法，页面加载成功以后就调用的方法）
const load = async () => {
	const res = await request.get('/video/collect/page', {
		params: {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			uid: uid.value,
			vid: vid.value
		}
	})
	pageNum.value = res.data.current
	pageSize.value = res.data.size
	total.value = res.data.total
	tableData.value = res.data.records
	//   userList
	const resuser = await request.get(`/user`)
	userList.value = resuser.data
	//   videoList
	const resvideo = await request.get(`/video`)
	videoList.value = resvideo.data
}

// 加载页面初始化调用load方法
load()

// 清空查询数据重置方法
const handleReset = () => {
	uid.value = ''
	vid.value = ''
	load()
}
// 修改每页展示的数据量方法
const handleSizeChange = size => {
	pageSize.value = size
	load()
}
// 翻页方法
const handleCurrentChange = current => {
	pageNum.value = current
	load()
}
// 多选按钮处理方法
const handleSelectionChange = val => {
	multipleSelection.value = val
	disabled.value = val.length === 0
}

// 关闭弹框提示方法
const handleClose = done => {
	ElMessageBox.confirm('确定关闭窗口?')
		.then(() => {
			handleResetForm(ruleFormRef.value)
		})
		.then(() => {
			done()
		})
		.catch(() => {
			// catch error
		})
}

// 提交表单校验方法
const handleSubmitForm = async formEl => {
	if (!formEl) {
		return
	}

	await formEl.validate(async (valid, fields) => {
		if (valid) {
			await request({
				method: form.id ? 'put' : 'post',
				url: form.id ? `/video/collect/${form.id}` : '/video/collect',
				data: form
			})
			ElMessage({
				showClose: true,
				message: '操作成功',
				type: 'success'
			})
			await handleResetForm(formEl)
		} else {
			console.log('error submit!', fields)
		}
	})
}
// 批量导入读数据写到后端数据库中
const beforeBatchUpload = async file => {
	let fd = new FormData()
	fd.append('file', file)
	await request.post('/video/collect/batch/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	await load()
}
// 批量导出方法
const handleBatchExport = async () => {
	const ids = multipleSelection.value.map(row => row.id)
	const res = await request(
		{
			url: `/video/collect/batch/export/${ids}`,
			method: 'get',
			responseType: 'blob'
		} //在请求中加上这一行，特别重要
	)
	downloadExcel(res, '导出数据表')
}
// 取消弹框方法
const handleResetForm = async formEl => {
	if (!formEl) {
		return
	}
	formEl.resetFields()

	Object.assign(form, {
		id: undefined,
		uid: undefined,
		vid: undefined,
		createTime: undefined
	})
	// formEl.clearValidate("img")
	dialogVisible.value = false
	await load()
}

// 文件上传方法

// 文件下载
const dowload = async url => {
	window.open(url)
}
// 富文本文件上传
const onUploadImg = async (files, callback) => {
	let i = 0
	const res = await Promise.all(
		files.map(file => {
			if (i > 0) {
				return false
			}
			return new Promise((rev, rej) => {
				const formdata = new FormData()
				formdata.append('file', file)

				request
					.post('/file/upload', formdata, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					})
					.then(res => {
						i++
						rev(res.data)
					})
					.catch(error => rej(error))
			})
		})
	)
	callback(res)
}
</script>

<style scoped lang="scss">
.el-form--inline .el-form-item {
	margin-right: 10px;
}

.form_header {
	background-color: #666666;
}

.pagination {
	margin-top: 10px;
}

.my-header {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
}
</style>
